<template>
  <div class="category-section discover-category-section">
    <div 
      class="category-list discover-category-list" 
      @touchstart.stop="categoryTouchStart" 
      @touchmove.stop="categoryTouchMove"
      @touchend.stop="categoryTouchEnd"
      @mousedown.stop="categoryMouseStart"
      @mousemove.stop="categoryMouseMove"
      @mouseup.stop="categoryMouseEnd"
      @mouseleave.stop="categoryMouseEnd"
      ref="categoryList"
    >
      <div 
        class="category-wrapper"
        :style="{ 
          transform: `translateX(${categoryOffset}px)`,
          transition: isCategorySliding ? 'none' : 'transform 0.3s ease' 
        }"
      >
        <div 
          class="category-item" 
          v-for="(category, index) in categories" 
          :key="index"
          :class="{ active: currentCategory === index }"
          @click="switchCategory(index)"
        >
          {{category}}
        </div>
      </div>
      <div class="dropdown-arrow" @click="toggleDropdown">
        <svg class="arrow-icon" aria-hidden="true">
          <use xlink:href="#icon-linecar105"></use>
        </svg>
      </div>
      <!-- 频道弹窗用teleport传送到body下，fixed定位 -->
      <teleport to="body">
        <div v-if="isDropdownOpen" class="category-dropdown-mask" @click.self="closeDropdown">
          <div class="category-dropdown-panel">
            <div class="dropdown-header">
              <span style="font-size:33px;font-weight:bold;">我的频道</span>
              <span class="dropdown-tip">点击进入频道</span>
              <button class="dropdown-close" @click="closeDropdown">×</button>
            </div>
            <div class="dropdown-block-list">
              <div class="dropdown-block" v-for="(item, idx) in myChannels" :key="'my-'+idx">
                <span style="font-size:23px;">{{item}}</span>
              </div>
            </div>
            <div class="dropdown-title" style="font-size:33px;font-weight:bold;margin:40px 0 20px 40px;">
              推荐频道 <span class="dropdown-tip">点击添加频道</span>
            </div>
            <div class="dropdown-block-list">
              <div class="dropdown-block" v-for="(item, idx) in recommendChannels" :key="'rec-'+idx">
                <span style="font-size:23px;">+ {{item}}</span>
              </div>
            </div>
          </div>
        </div>
      </teleport>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  name: 'CategorySelector',
  props: {
    categories: {
      type: Array,
      required: true
    },
    currentCategory: {
      type: Number,
      required: true
    }
  },
  setup(props, { emit }) {
    const categoryList = ref(null);
    const categoryOffset = ref(0);
    const isCategorySliding = ref(false);
    const categoryStartX = ref(0);
    const categoriesWidth = ref(0);
    const categoryContentWidth = ref(0);
    const isDropdownOpen = ref(false);
    // 新增频道数据（可后续改为动态）
    const myChannels = ref([
      '推荐', '直播', '短剧', '科技数码', '旅行', '美食', '头像', '汽车',
      '摄影', '家装', '壁纸', '穿搭', '家居', '情感', '舞蹈', '学习',
      '影视', '音乐', '游戏', '男士理容', '艺术', '动漫', '搞笑'
    ]);
    const recommendChannels = ref([
      '读书', '职场', '科学', '绘画', '潮鞋', '减脂', '健身', '护肤',
      '手工', '婚礼', '明星', '萌宠', '文化', '机车', '竞技', '心理',
      '户外', '母婴', '社科', '校园', '体育', '潮玩', '露营', '考艺'
    ]);

    // 切换类别
    const switchCategory = (index) => {
      emit('update:currentCategory', index);
    };

    // 切换下拉菜单
    const toggleDropdown = () => {
      isDropdownOpen.value = !isDropdownOpen.value;
      // 这里可以添加展开更多分类的逻辑
    };

    // 触摸相关函数
    const categoryTouchStart = (e) => {
      isCategorySliding.value = true;
      categoryStartX.value = e.touches[0].clientX;
      
      if (!categoriesWidth.value && categoryList.value) {
        categoriesWidth.value = categoryList.value.offsetWidth;
        
        // 计算所有类别项的总宽度
        const items = categoryList.value.querySelectorAll('.category-item');
        categoryContentWidth.value = 0;
        items.forEach(item => {
          categoryContentWidth.value += item.offsetWidth;
        });
      }
    };

    const categoryTouchMove = (e) => {
      if (!isCategorySliding.value) return;
      
      // 计算偏移量
      const currentX = e.touches[0].clientX;
      let newOffset = categoryOffset.value + (currentX - categoryStartX.value);
      
      // 限制滑动范围
      if (newOffset > 0) {
        newOffset = 0;
      } else if (categoryContentWidth.value > categoriesWidth.value && 
                newOffset < -(categoryContentWidth.value - categoriesWidth.value)) {
        newOffset = -(categoryContentWidth.value - categoriesWidth.value);
      }
      
      categoryOffset.value = newOffset;
      categoryStartX.value = currentX;
    };

    const categoryTouchEnd = () => {
      isCategorySliding.value = false;
    };

    // 鼠标相关函数
    const categoryMouseStart = (e) => {
      isCategorySliding.value = true;
      categoryStartX.value = e.clientX;
      
      if (!categoriesWidth.value && categoryList.value) {
        categoriesWidth.value = categoryList.value.offsetWidth;
        
        // 计算所有类别项的总宽度
        const items = categoryList.value.querySelectorAll('.category-item');
        categoryContentWidth.value = 0;
        items.forEach(item => {
          categoryContentWidth.value += item.offsetWidth;
        });
      }
    };

    const categoryMouseMove = (e) => {
      if (!isCategorySliding.value) return;
      
      // 计算偏移量
      const currentX = e.clientX;
      let newOffset = categoryOffset.value + (currentX - categoryStartX.value);
      
      // 限制滑动范围
      if (newOffset > 0) {
        newOffset = 0;
      } else if (categoryContentWidth.value > categoriesWidth.value && 
                newOffset < -(categoryContentWidth.value - categoriesWidth.value)) {
        newOffset = -(categoryContentWidth.value - categoriesWidth.value);
      }
      
      categoryOffset.value = newOffset;
      categoryStartX.value = currentX;
    };

    const categoryMouseEnd = () => {
      isCategorySliding.value = false;
    };

    // 关闭弹窗
    const closeDropdown = () => {
      isDropdownOpen.value = false;
    };

    return {
      categoryList,
      categoryOffset,
      isCategorySliding,
      switchCategory,
      toggleDropdown,
      isDropdownOpen,
      myChannels,
      recommendChannels,
      closeDropdown,
      categoryTouchStart,
      categoryTouchMove,
      categoryTouchEnd,
      categoryMouseStart,
      categoryMouseMove,
      categoryMouseEnd
    };
  }
}
</script>

<style scoped lang="less">
.discover-category-section {
  border-top: 1px solid #e4e4e4;
  position: sticky;
  top: -1px;
  z-index: 100;
  background-color: #fff;
  
  .section-header {
    padding: 0 15px;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
    position: relative;
  }
  
  .discover-category-list {
    position: relative !important;
    height: 82px;
    overflow: hidden;
    
    .category-wrapper {
      display: flex;
      padding: 0 40px;
      height: 100%;
      
      .category-item {
        position: relative;
        font-size: 27px;
        white-space: nowrap;
        line-height: 82px;
        color: #7a7a7a;
        margin-right: 55px;
        
        &:last-child {
          margin-right: 0;
        }
        
        &.active {
          font-weight: bold;
          color: #000;
        }
      }
    }
    
    .dropdown-arrow {
      position: absolute;
      top: 0;
      right: 0;
      height: 82px;
      width: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(to right, rgba(255,255,255,0), rgba(255,255,255,1) 30%);
      z-index: 10;
      cursor: pointer;
      .arrow-icon{
        width: 40px;
        height: 40px;
      }
    }
  }
}

.category-dropdown-mask {
  position: fixed !important;
  top: 100px;
  left: 0;
  width: 100vw;
  background: none;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
.category-dropdown-panel {
  margin-top: 0;
  background: #fff;
  border-radius: 32px 32px 0 0;
  width: 100vw;
  max-width: 750px;
  padding: 40px 0 40px 0;
  box-sizing: border-box;
  min-height: 70vh;
  position: relative;
}
.dropdown-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0 40px 0 40px;
  font-size: 33px;
  font-weight: bold;
  margin-bottom: 30px;
  position: relative;
  height: 50px;
}
.dropdown-header .dropdown-tip {
  font-size: 20px;
  color: #bdbdbd;
  font-weight: normal;
  margin-left: 18px;
}
.dropdown-close {
  position: absolute;
  right: 20px;
  top: 0;
  font-size: 40px;
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  line-height: 1;
}
.dropdown-title {
  font-size: 33px;
  font-weight: bold;
  margin: 40px 0 20px 40px;
  display: flex;
  align-items: center;
}
.dropdown-title .dropdown-tip {
  font-size: 20px;
  color: #bdbdbd;
  font-weight: normal;
  margin-left: 18px;
}
.dropdown-block-list {
  display: flex;
  flex-wrap: wrap;
  padding: 0 20px 0 40px;
}
.dropdown-block {
  width: 152px;
  height: 85px;
  background: #fff;
  border: 1.5px solid #e4e4e4;
  border-radius: 18px;
  margin: 0 18px 22px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 23px;
  color: #222;
  box-sizing: border-box;
  font-weight: 500;
  cursor: pointer;
  transition: box-shadow 0.2s;
}
.dropdown-block:last-child {
  margin-right: 0;
}
</style> 